package com.tcm.ucenter.service;

import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.ObjectUtil;
import com.tcm.core.service.ConfigService;
import com.tcm.ucenter.domain.dto.UserAccountDTO;
import com.tcm.ucenter.domain.entity.PointsDeduction;
import com.tcm.ucenter.mapper.PointsDeductionMapper;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@DubboService(version = "0.0.1-alpha", delay = -1, retries = 3)
public class PointsDeductionServiceImpl implements PointsDeductionService {

    @Autowired
    private PointsDeductionMapper pointsDeductionMapper;

    @DubboReference(version = "0.0.1-alpha", timeout = 6000, retries = 3, check = false)
    private UserAccountService userAccountService;

    @DubboReference(version = "0.0.1-alpha", timeout = 6000, retries = 3, check = false)
    private ConfigService configService;

    @Override
    public Map<String, Object> usablePoint(Long userId, BigDecimal price) {
        BigDecimal deduction = new BigDecimal("0");
        Map<String, Object> map = new HashMap<>();
        List<PointsDeduction> pointsDeductions = pointsDeductionMapper.selectList();
        for (PointsDeduction pointsDeduction : pointsDeductions) {
            if (NumberUtil.isGreaterOrEqual(pointsDeduction.getLimitPrice(), price)) {
                deduction = pointsDeduction.getPointsDeduction();
                break;
            }
        }
        Integer deductionAmount = NumberUtil.round(NumberUtil.mul(price, deduction), 0).intValue();

        //积分兑换比例
        Integer point_deduction = Integer.valueOf(configService.findValue("point_deduction", "1"));
        Integer needPoint = NumberUtil.round(NumberUtil.mul(point_deduction, deductionAmount), 0).intValue();

        UserAccountDTO userAccountVo = userAccountService.findByUserId(userId);
        Integer userPoint = 0;
        if (ObjectUtil.isNotNull(userAccountVo)) {
            userPoint = userAccountVo.getPoint();
        }
        map.put("deductionAmount", deductionAmount);
        map.put("userPoint", userPoint);
        map.put("needPoint", needPoint);
        return map;
    }
}
//*/
